//
//  QianliResetUserpwVC.swift
//  todoios
//
//  Created by qianli on 2025/5/23.
//

import Foundation
import SwiftyUserDefaults

class QianliResetUserpwVC: QianliParentNaviVC {
    private var cWTPhgOUvVenvUrY: InputMailView?
    private var XObbAmti41Z1DqGB: InputMailView?
    private var viVV4GQEwb5QJDfC: InputPasswordView?
    private var UMKeiocxEjcTkHfF: GradientBtn?
    private var tSDTdfTJsO37dEQz:UIButton?
    private var mMj5rlMV98SudqQ4:Timer?
    private var FfoMKDHgYvZ7WEyB:Int = 60
    var resetOKBlock:((_ mail:String)->Void)?
    
    
    override func GHL4Rhb91XYBer27() {
        self.zdMpsGrNncVEHdYA(title: LocalizedString("Reset Password"))
        let logoView = UIImageView(frame: CGRect(x: qianli_pm_width/2 - 80/2, y: topSpace+15, width: 80, height: 80))
        view.addSubview(logoView)
        logoView.image = "qianli_logo_main".qianli_R_image
        
        var iTop = topSpace+15+80+30
        self.cWTPhgOUvVenvUrY = InputMailView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60) , icoName: "qianli_field_email", placeholder: LocalizedString("Please enter a email"), showclear: true)
        if let inputmail = self.cWTPhgOUvVenvUrY{
            view.addSubview(inputmail)
            inputmail.backgroundColor = .systemBackground
            inputmail.layer.cornerRadius = 30
            let username = Defaults[\.username]
            if !username.isEmpty{
                inputmail.oC2j3DaaYowlc1xU(Defaults[\.username])
            }
        }
        
        iTop+=60+20
        self.XObbAmti41Z1DqGB = InputMailView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70-90, height: 60) , icoName: "qianli_field_code", placeholder: LocalizedString("Please enter e-code"), showclear: false)
        if let inputcode = self.XObbAmti41Z1DqGB{
            view.addSubview(inputcode)
            inputcode.backgroundColor = .systemBackground
//            inputcode.layer.cornerRadius = 30
            inputcode.qianli_round_rect(corner: [.topLeft,.bottomLeft], radii: CGSize(width: 30, height: 30))
        }
        self.tSDTdfTJsO37dEQz = UIButton(frame: CGRect(x: qianli_pm_width-35-100, y: iTop, width: 100, height: 60))
        if let btnCode = self.tSDTdfTJsO37dEQz{
            view.addSubview(btnCode)
            btnCode.setTitle(LocalizedString("GET CODE"), for: .normal)
            btnCode.setTitleColor(.systemBlue, for: .normal)
            btnCode.backgroundColor = .systemBackground
//            btnCode.layer.cornerRadius = 30
            btnCode.qianli_round_rect(corner: [.topRight,.bottomRight], radii: CGSize(width: 30, height: 30))
            btnCode.titleLabel?.font = .systemFont(ofSize: 13)
            btnCode.touch_With_Block { [weak self]sender in
                self?.Vsp15DYMJGKZwKUn()
            }
        }
        iTop+=60+20
        self.viVV4GQEwb5QJDfC = InputPasswordView(frame:CGRect(x: 35, y: iTop, width: qianli_pm_width-70, height: 60),placeholder: LocalizedString("Enter 4-digit password"))
        if let inputpw = self.viVV4GQEwb5QJDfC{
            view.addSubview(inputpw)
            inputpw.backgroundColor = .systemBackground
            inputpw.layer.cornerRadius = 30
        }
        
        iTop+=60+30
        self.UMKeiocxEjcTkHfF = GradientBtn(frame: CGRect(x: 40, y: iTop, width: qianli_pm_width-80, height: 48), title: LocalizedString("SURE"))
        if let loginBtn = self.UMKeiocxEjcTkHfF{
            view.addSubview(loginBtn)
            loginBtn.touch_With_Block { [weak self] sender in
                self?.I78xJTIx1AbmwUKi()
            }
        }
        
        iTop+=20+50
        let kefuBtn = UIButton(frame: CGRect(x: qianli_pm_width/2-60, y: iTop, width: 120, height: 20))
        view.addSubview(kefuBtn)
        kefuBtn.setTitle(LocalizedString("LINK US"), for: .normal)
        kefuBtn.setTitleColor(UIColor(hexString: "#3964ff"), for: .normal)
        kefuBtn.titleLabel?.font = .systemFont(ofSize: 13)
        kefuBtn.touch_With_Block { sender in
            let customUrl = Defaults[\.customerURL]
            QianliUniversalFunc.PqHXCLMrbGaK2xN1(customUrl) { success in
            }
        }
    }
}

extension QianliResetUserpwVC{
    func Vsp15DYMJGKZwKUn(){
        self.view.endEditing(true)
        
        guard let inputmail = self.cWTPhgOUvVenvUrY else{
            return
        }
        let s_mail = inputmail.JRrMFFk8vXgbNlUN()
        if s_mail.isEmpty || !isValidEmail(s_mail){
            self.view.Qianli_Toast(LocalizedString("Please enter a valid email"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        if let btn=self.tSDTdfTJsO37dEQz{
            btn.isEnabled = false
        }
        // email_type可选值："EMAIL_TYPE_USER_REGISTER" "EMAIL_TYPE_USER_RESETPWD" "EMAIL_TYPE_TEST"
        let emailRequest = EmailCodeRequest(email_type: "EMAIL_TYPE_USER_RESETPWD", target_email: s_mail)
        LoginViewModel.shared.ogOuZmnc3tTKZf96(emailCodeRequest: emailRequest){result in
            DispatchQueue.main.async {[weak self] in
                switch (result){
                case .success(let data):
                    if data.code == 0{
                        self?.h2TxvkkqORtyv725("")
                    }else{
                        self?.h2TxvkkqORtyv725(data.msg)
                    }
                case .failure(let error):
                    self?.h2TxvkkqORtyv725("\(LocalizedString("Get email code failed"))：\(error.localizedDescription)")
                }
            }
        }
    }
    
    func h2TxvkkqORtyv725(_ errMsg:String){
        if errMsg.isEmpty{
            self.view.Qianli_Toast(LocalizedString("An email code has sent,please checkout!"))
            //开始倒计时
            vYwwyLv2Lsx8oZ39()
        }else{
            //关闭倒计时
            self.view.Qianli_Toast(errMsg)
            if let btn=self.tSDTdfTJsO37dEQz{
                btn.isEnabled = true
            }
        }
    }
    
    func vYwwyLv2Lsx8oZ39(){
        if let btn = self.tSDTdfTJsO37dEQz{
            btn.isEnabled = false
        }
        Vsxa9l8jUKigDSiL()
        
        self.mMj5rlMV98SudqQ4 = Timer(timeInterval: 1, repeats: true, block: {[weak self] _ in
            if let self = self{
//                DispatchQueue.main.async { //任务可能因为诸如滚动UI时延迟执行，但不会中断
                    self.FfoMKDHgYvZ7WEyB -= 1
                    if self.FfoMKDHgYvZ7WEyB <= 0{
                        self.Vsxa9l8jUKigDSiL()
                    }else if let btn=self.tSDTdfTJsO37dEQz{
                        btn.setTitle("\(self.FfoMKDHgYvZ7WEyB)", for: .normal)
                    }
                }
//            }
        })
        if let timer = self.mMj5rlMV98SudqQ4{
            RunLoop.main.add(timer, forMode: .common) //确保在滚动等操作时 Timer 不中断
            timer.fire()
        }
    }
    
    func Vsxa9l8jUKigDSiL(){
        if let timer = self.mMj5rlMV98SudqQ4{
            timer.invalidate()
        }
        self.mMj5rlMV98SudqQ4 = nil
        if let btn = self.tSDTdfTJsO37dEQz{
            btn.isEnabled = true
            btn.setTitle(LocalizedString("GET CODE"), for: .normal)
        }
        self.FfoMKDHgYvZ7WEyB = 60
    }
    
    func I78xJTIx1AbmwUKi(){
        view.endEditing(true)
        
        guard let btnResetr = self.UMKeiocxEjcTkHfF else{//,btnRegister.tag != 10
            return
        }
        
        guard let inputmail = self.cWTPhgOUvVenvUrY,let inputpw = self.viVV4GQEwb5QJDfC,let inputcode = self.XObbAmti41Z1DqGB else{
            return
        }
        
        let s_mail = inputmail.JRrMFFk8vXgbNlUN()
        if s_mail.isEmpty || !isValidEmail(s_mail){
            self.view.Qianli_Toast(LocalizedString("Please enter a valid email"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        let s_pw = inputpw.JRrMFFk8vXgbNlUN()
        if s_pw.isEmpty || s_pw.count<4{
            self.view.Qianli_Toast(LocalizedString("Please enter a valid password"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        let s_code = inputcode.JRrMFFk8vXgbNlUN()
        if s_code.isEmpty || s_pw.count<4{
            self.view.Qianli_Toast(LocalizedString("Please enter email code"))
            QianliVibrateEnum.oldSchool.vibrate()
            return
        }
        btnResetr.setTitle(LocalizedString("Password Resetting..."), for: .normal)
        btnResetr.isEnabled = false
        
        let deviceid = getDeviceID()
        
        let passRequest = ResetPasswordRequest(device_id: deviceid, email_code: s_code, password: s_pw, user_name: s_mail)
        LoginViewModel.shared.rqw7MMQYipwKZmYo(resetPassword: passRequest) { result in
            DispatchQueue.main.async {[weak self] in
                switch result {
                case .failure(let error):
                    self?.HGt47eHgIFbSUP50("\(LocalizedString("Reset Password Failed"))：\(error.localizedDescription)")
                case .success(let resetResult):
                    if resetResult.code == 0{
//                        {"code":0,"msg":"密码重置成功","data":null}
                        self?.HGt47eHgIFbSUP50("")
                    }else{
                        self?.HGt47eHgIFbSUP50(resetResult.msg)
                    }
                }
            }
        }
    }
    
    func HGt47eHgIFbSUP50(_ msg:String){
        if let btn = self.UMKeiocxEjcTkHfF{
            btn.isEnabled = true
            btn.setTitle(LocalizedString("SURE"), for: .normal)
        }
//密码已重置，请重新登录
        if msg.isEmpty{
            self.clFi25NuDNbscWXL()
            if let inputmail = self.cWTPhgOUvVenvUrY{
                let s_mail = inputmail.JRrMFFk8vXgbNlUN()
                resetOKBlock?(s_mail)
            }
        }else{
            self.view.Qianli_Toast(msg)
        }
    }
}
